<template>
  <div class="publish-info">
    <div class="operation-bar">
      <el-button type="primary" @click="toggleUpdate" :loading="updating">
        {{ updateEnabled ? '禁用' : '启用' }}更新发布信息
      </el-button>
    </div>
    <h1>发布信息</h1>
    
    <div class="search-bar">
      <el-input 
        v-model="searchOwner" 
        placeholder="组织名称" 
        clearable 
        @input="searchPublishInfos"
      />
      <el-input 
        v-model="searchName" 
        placeholder="库名称" 
        clearable 
        @input="searchPublishInfos"
      />
      <el-button type="primary" @click="searchPublishInfos">
        <el-icon><Search /></el-icon>
      </el-button>
      <el-button @click="resetSearch">重置</el-button>
      <el-button type="primary" @click="showAddDialog">添加发布信息</el-button>
      <el-button type="success" @click="handleBatchPublish" :disabled="!selectedRows.length">
        批量发布
      </el-button>
    </div>
    
    <!-- 在 el-table 的 :data 属性中修改数据源 -->
    <!-- 修改表格列，使用索引作为行号 -->
    <el-table :data="paginatedData" style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" width="60">
        <template #default="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="owner" label="组织名称" width="120" />
      <el-table-column prop="name" label="库名称" width="120" />
      <!-- 其他列保持不变 -->
      <el-table-column prop="publisher" label="发布者" width="100" />
      <el-table-column prop="version" label="发布版本" width="100" /> 
      <el-table-column prop="commitId" label="CommitID" min-width="150" show-overflow-tooltip />
      <el-table-column prop="changeLog" label="Changelog" min-width="200">
        <template #default="scope">
          <div class="changelog-container">
            <div class="changelog-content">{{ scope.row.changeLog }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="备注" min-width="120" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deletePublishInfo(scope.row.id)">删除</el-button>
          <el-button 
            size="small" 
            type="success" 
            @click="handlePublish(scope.row)"
            :disabled="scope.row.status === '审核中'">
            发布
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 添加/编辑发布信息对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑发布信息' : '添加发布信息'">
      <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
        <el-form-item 
          label="组织名称" 
          prop="owner"
          :rules="[
            { required: true, message: '请选择组织名称', trigger: 'change' }
          ]">
          <el-select v-model="form.owner" placeholder="请选择组织名称">
            <el-option label="openharmony-sig" value="openharmony-sig" />
            <el-option label="openharmony-tpc" value="openharmony-tpc" />
            <el-option label="openharmony_tpc_samples" value="openharmony_tpc_samples" />
          </el-select>
        </el-form-item>
        <el-form-item 
          label="库名称" 
          prop="name"
          :rules="[
            { required: true, message: '请输入库名称', trigger: 'blur' }
          ]">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="发布者">
          <el-input v-model="form.publisher" />
        </el-form-item>
        <el-form-item label="发布版本">
          <el-input v-model="form.version" />
        </el-form-item>
        <el-form-item label="CommitID">
          <el-input v-model="form.commitId" />
        </el-form-item>
        <el-form-item label="Changelog">
          <el-input v-model="form.changeLog" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="未发布" value="未发布" />
            <el-option label="审核中" value="审核中" />
            <el-option label="发布失败" value="发布失败" />
            <el-option label="审核通过" value="审核通过" />
            <el-option label="审核被打回" value="审核被打回" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePublishInfo">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 添加分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="publishInfos.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <!-- 添加发布进度组件 -->
  <publish-progress ref="publishProgressRef" />
  <!-- 替换单个进度组件为动态多窗口 -->
  <template v-for="dialog in publishDialogs" :key="dialog.id">
    <publish-progress
      :dialog-id="dialog.id"
      :owner="dialog.owner"
      :name="dialog.name"
      @close="closePublishDialog"
      ref="publishDialogs"
    />
  </template>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { publishInfoApi } from '../api'
import { ref, onMounted, computed } from 'vue'
import PublishProgress from '../components/PublishProgress.vue'

export default {
  name: 'PublishInfo',
  components: {
    Search,
    PublishProgress 
  },
  methods: {
    async handlePublish(item) {
      try {
        // 显示进度对话框
        this.$refs.publishProgressRef.show()
        
        // 发起发布请求
        const response = await publishInfoApi.publish({
          owner: item.owner,
          name: item.name
        })
        
        if (response.data) {
          this.$message.success('发布成功')
        } else {
          this.$message.error('发布失败')
        }
      } catch (error) {
        this.$message.error(`发布失败: ${error.message}`)
      } finally {
        // 隐藏进度对话框
        this.$refs.publishProgressRef.hide()
      }
    }
  },
  setup() {
    const selectedRows = ref([])
    const publishProgressRef = ref(null)
    const publishDialogs = ref([])
    const publishInfos = ref([])
    const formRef = ref(null)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const loading = ref(false)
    const updating = ref(false)
    const updateEnabled = ref(false)
    const searchOwner = ref('')
    const searchName = ref('')
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const form = ref({
      id: null,
      owner: '',
      name: '',
      version: '',
      publisher: '',
      commitId: '',
      changeLog: '',
      title: '',
      status: '未发布'
    })

    const getStatusType = (status) => {
      const statusMap = {
        '未发布': 'info',
        '发布中': 'warning',
        '审核中': 'warning',
        '发布失败': 'danger',
        '审核通过': 'success',
        '审核被打回': 'danger'
      }
      return statusMap[status] || 'info'
    }

    // 添加选择行变化处理方法
    const handleSelectionChange = (rows) => {
      selectedRows.value = rows
    }

    // 添加单个发布处理方法
    const handlePublish = async (row) => {
      try {
        await ElMessageBox.confirm('确定要发布这条信息吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        publishProgressRef.value.show()  // 显示进度对话框
        publishProgressRef.value.updateProgress('PREPARING', '准备发布...')

        const publishData = {
          owner: row.owner,
          name: row.name,
          id: row.id
        }
        
        const response = await publishInfoApi.publish(publishData)
        
        if (response?.data?.success) {
          publishProgressRef.value.updateProgress('COMPLETED', '发布成功！')
          await loadPublishInfos()
        } else {
          publishProgressRef.value.updateProgress('FAILED', '发布失败：' + (response?.data?.message || '未知错误'))
          ElMessage.error('发布失败，请检查系统日志')
        }
      } catch (error) {
        if (error !== 'cancel') {
          publishProgressRef.value?.updateProgress('FAILED', '发布失败：' + (error.response?.data?.message || error.message || '未知错误'))
          console.error('发布失败，详细错误:', error.response?.data || error)
          ElMessage.error(`发布失败: ${error.response?.data?.message || error.message || '未知错误'}`)
        }
      }
    }

    // 修改批量发布处理方法
    const handleBatchPublish = async () => {
      if (!selectedRows.value.length) {
        ElMessage.warning('请选择要发布的信息')
        return
      }

      try {
        await ElMessageBox.confirm(
          `确定要发布选中的 ${selectedRows.value.length} 条信息吗？`, 
          '提示', 
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        publishProgressRef.value.show()
        publishProgressRef.value.updateProgress('PREPARING', '准备批量发布...')

        const publishItems = selectedRows.value.map(row => ({
          owner: row.owner,
          name: row.name
        }))
        
        const response = await publishInfoApi.batchPublish(publishItems)
        if (response?.data?.success) {
          publishProgressRef.value.updateProgress('COMPLETED', '批量发布成功！')
          await loadPublishInfos()
          ElMessage.success('批量发布成功')
        } else {
          publishProgressRef.value.updateProgress('FAILED', '批量发布失败：' + (response?.data?.message || '未知错误'))
          ElMessage.error('批量发布失败，请检查系统日志')
        }
      } catch (error) {
        if (error !== 'cancel') {
          publishProgressRef.value?.updateProgress('FAILED', '批量发布失败：' + (error.response?.data?.message || error.message || '未知错误'))
          console.error('批量发布失败:', error)
          ElMessage.error(`批量发布失败: ${error.response?.data || error.message || '未知错误'}`)
        }
      }
    }

    // 添加关闭窗口方法
    const closePublishDialog = (dialogId) => {
      const index = publishDialogs.value.findIndex(d => d.id === dialogId)
      if (index > -1) {
        publishDialogs.value.splice(index, 1)
      }
    }

    const getUpdateStatus = async () => {
      try {
        const response = await publishInfoApi.getUpdateStatus()
        updateEnabled.value = response.data
      } catch (error) {
        console.error('获取更新状态失败:', error)
      }
    }

    // 添加分页处理方法
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
    }

    // 添加分页数据计算属性
    const paginatedData = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return publishInfos.value.slice(start, end)
    })

    const toggleUpdate = async () => {
      updating.value = true
      try {
        const response = await publishInfoApi.toggleUpdate()
        console.log('Toggle update response:', response)
        updateEnabled.value = response.data
        ElMessage.success(`${updateEnabled.value ? '启用' : '禁用'}更新功能成功`)
      } catch (error) {
        console.error('切换更新状态失败:', error.response || error) // 修改这行
        ElMessage.error(`切换更新状态失败: ${error.response?.data?.message || error.message}`)
      } finally {
        updating.value = false
      }
    }

    const loadPublishInfos = async () => {
      loading.value = true
      try {
        const response = await publishInfoApi.getAll()
        publishInfos.value = response.data
      } catch (error) {
        console.error('加载发布信息失败:', error)
        ElMessage.error('加载发布信息失败')
      } finally {
        loading.value = false
      }
    }

    const searchPublishInfos = async () => {
      if (!searchOwner.value && !searchName.value) {
        loadPublishInfos()
        return
      }
      
      loading.value = true
      try {
        const response = await publishInfoApi.getByOwnerAndName(searchOwner.value, searchName.value)
        publishInfos.value = response.data
      } catch (error) {
        console.error('搜索发布信息失败:', error)
        ElMessage.error('搜索发布信息失败')
      } finally {
        loading.value = false
      }
    }

    const resetSearch = () => {
      searchOwner.value = ''
      searchName.value = ''
      loadPublishInfos()
    }

    const showAddDialog = () => {
      isEdit.value = false
      form.value = {
        id: null,
        owner: '',
        name: '',
        version: '',
        developer: '',
        commitId: '',
        title: '',
        status: '未发布'
      }
      dialogVisible.value = true
    }

    const showEditDialog = (publishInfo) => {
      isEdit.value = true
      form.value = { ...publishInfo }
      dialogVisible.value = true
    }

    const savePublishInfo = async () => {
    if (!formRef.value) return
    
    try {
        await formRef.value.validate()
        if (isEdit.value) {
            const response = await publishInfoApi.update(form.value.id, form.value)
            if (response.data) {  // 添加响应检查
                ElMessage.success('发布信息更新成功')
                dialogVisible.value = false
                loadPublishInfos()
            } else {
                ElMessage.error('保存失败，请检查数据')
            }
        } else {
            const response = await publishInfoApi.create(form.value)
            if (response.data) {  // 添加响应检查
                ElMessage.success('发布信息添加成功')
                dialogVisible.value = false
                loadPublishInfos()
            } else {
                ElMessage.error('保存失败，请检查数据')
            }
        }
    } catch (error) {
        console.error('保存发布信息失败:', error)
        ElMessage.error(`保存失败: ${error.response?.data?.message || error.message || '未知错误'}`)
    }
}

    const deletePublishInfo = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除这条发布信息吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await publishInfoApi.delete(id)
        ElMessage.success('发布信息删除成功')
        loadPublishInfos()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除发布信息失败:', error)
          ElMessage.error('删除发布信息失败')
        }
      }
    }

    onMounted(() => {
      console.log('publishProgressRef:', publishProgressRef.value) // 检查组件
      loadPublishInfos()
      getUpdateStatus()
    })

    return {
      publishInfos,
      loading,
      searchOwner,
      searchName,
      dialogVisible,
      isEdit,
      form,
      updating,
      updateEnabled,
      currentPage,
      pageSize,
      paginatedData,
      selectedRows,
      formRef,
      publishProgressRef,
      publishDialogs,
      closePublishDialog,
      handleSelectionChange,
      handlePublish,
      handleBatchPublish,
      handleSizeChange,
      handleCurrentChange,
      toggleUpdate,
      getStatusType,
      loadPublishInfos,
      searchPublishInfos,
      resetSearch,
      showAddDialog,
      showEditDialog,
      savePublishInfo,
      deletePublishInfo
    }
  }
}
</script>

<style scoped>
.publish-info {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
  min-height: calc(100vh - 200px);
}

.changelog-container {
  max-height: 80px;
  overflow-y: auto;
  padding: 4px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.changelog-content {
  white-space: pre-line;
  word-break: break-word;
}

/* 自定义滚动条样式 */
.changelog-container::-webkit-scrollbar {
  width: 6px;
}

.changelog-container::-webkit-scrollbar-thumb {
  background-color: #909399;
  border-radius: 3px;
}

.changelog-container::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

.search-bar {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.search-bar .el-input {
  max-width: 200px;
}

.operation-bar {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  margin-bottom: 60px;
}

.publish-info {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
  min-height: calc(100vh - 200px);
}
</style>


    async manualUpdate() {
      try {
        this.manualUpdating = true;
        const response = await fetch('/api/publish-info/manual-update', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          this.$message.success('手动更新触发成功');
          // 刷新数据列表
          await this.loadPublishInfos();
        } else {
          this.$message.error('手动更新触发失败');
        }
      } catch (error) {
        console.error('手动更新出错:', error);
        this.$message.error('手动更新出错: ' + error.message);
      } finally {
        this.manualUpdating = false;
      }
    }
